// HSMKey.cpp: implementation of the HSMKey class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "SCRDLL.h"
#include "HSMKey.h"
#include "Function.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

HSMKey::HSMKey()
{
	m_IsKeyLoaded = FALSE;
}

HSMKey::~HSMKey()
{

}

#define EDK  "24655FD915C88EC4EA1B31106C45839A"

BOOL HSMKey::loadKey(LPCTSTR filePath)
{
	CStdioFile keyFile;
	if(!keyFile.Open(filePath, CFile::modeRead|CFile::typeText)) {
		return -1;
	}

	CString line;
	CString index;
	CString enKey;
	CString key;
	
	pair<map<CString, CString>::iterator, bool> insert_Pair;
	
	while (keyFile.ReadString(line)) {
		line.Remove(' ');

		if(line.GetLength() == 0) {
			continue;
		}
		
		AfxExtractSubString(index, line, 0, ',');
		AfxExtractSubString(enKey, line, 1, ',');

		int enKeyLen = enKey.GetLength();
		key = _des(EDK, enKey, "1");

		if(key.Mid(enKeyLen-16, 2) != "80") {
			keyFile.Close();
			return FALSE;
		}

		key = key.Left(enKeyLen-16);
		
		insert_Pair = m_KeyMap.insert(MAP_CSTRING_CSTRING::value_type(index, key));
		if(!insert_Pair.second) {
			keyFile.Close();
			return FALSE;
		}
	}
	
	keyFile.Close();
	m_IsKeyLoaded = TRUE;

	return TRUE;
}

BOOL HSMKey::findKey(LPCTSTR index, CString & key)
{
	MAP_CSTRING_CSTRING::iterator iter; 
	
	iter = m_KeyMap.find(index); 
	
	if (iter != m_KeyMap.end()) { 
		key = iter->second;
		return TRUE;
	}
	
	return FALSE;
}

BOOL HSMKey::wasKeyLoaded()
{
	return m_IsKeyLoaded;
}
